package com.transcargo.request;

import com.transcargo.action.ServletParametersException;
import com.transcargo.action.ServletValidationException;
import com.transcargo.db.db;
import com.transcargo.db.dbException;
import com.transcargo.geo.GeoObjectNotFoundException;
import com.transcargo.rating.Rating;
import com.transcargo.rpc.RPCOutput;
import com.transcargo.users.LongUser;
import com.transcargo.users.ShortUser;
import com.transcargo.users.User;
import com.transcargo.users.UserNotFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.PrintWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.StringTokenizer;

public class GetUserComboRequest extends Request
{
	private String uid = "";
	private String name = "";
	private String xml = "";
	private ShortUser[] users = null;
	
	private void search() throws SQLException, dbException, UserNotFoundException, GeoObjectNotFoundException {
		StringTokenizer tok = new StringTokenizer(name, " ");
		String[] tokens = new String[tok.countTokens()];
		int i = 0;
		while (tok.hasMoreTokens()) {
			tokens[i++] = tok.nextToken();
		}
		String query = "SELECT id FROM registered_users WHERE";
		for (i = 0; i < tokens.length; i++) {
			query = query + " organization=? OR organization REGEXP ? OR organization REGEXP ? OR organization REGEXP ?";
		}
		db.PreStatement pre = dbase.CreateStatement(query);
		for (i = 0; i < tokens.length; i++) {
			pre.Insert(tokens[i]);
			pre.Insert("^" + tokens[i] + "[[:space:][:punct:]]");
			pre.Insert("[[:space:][:punct:]]" + tokens[i] + "$");
			pre.Insert("[[:space:][:punct:]]" + tokens[i] + "[[:space:][:punct:]]");
		}
		list = dbase.execute(pre);
		iter = list.iterator();
		if (list.size() > 0) users = new ShortUser[list.size()]; else users = null;
		i = 0;
		while (iter.hasNext()) {
			String[] res = iter.next();
			users[i] = new ShortUser(Integer.parseInt(res[0]), dbase);
		}
		
	}

    private void servletGetValues(HttpServletRequest request) throws ServletParametersException {
		uid = request.getParameter("uid");
		if (uid == null) uid = "";
		name = request.getParameter("name");
		if (name == null) name = "";
    }
    private void servletValidateValues() throws ServletValidationException {
    	if (uid.length() == 0 && name.length() == 0) throw new ServletValidationException("Empty uid and name");
    }
    private void servletExecuteRequest() throws ServletRequestException {
    	try {
    		if (name.length() > 2) {
    			search();
    			xml =  RPCOutput.generate(users);
    		} else if (uid.length() > 0 && !uid.equals("0")) {
    			LongUser user = new LongUser(Integer.parseInt(uid), dbase);
    			xml =  RPCOutput.generate(user);
    		} else throw new ServletRequestException();
    	} catch (GeoObjectNotFoundException e) {
    		throw new ServletRequestException();
    	} catch (UserNotFoundException e) {
    		throw new ServletRequestException();
		} catch (SQLException e) {
    		throw new ServletRequestException();
		} catch (dbException e) {
    		throw new ServletRequestException();
		}
    }
    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        PrintWriter out = null;
		try {
            out = response.getWriter();
            servletGetValues(request);
            servletValidateValues();
            servletExecuteRequest();
            out.println(xml);
	    } catch (ServletParametersException e) {
           sendRedirect(response, "index.jsp");
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletRequestException e) {
            String xml =  RPCOutput.generate(false);
            out.println(xml);
        }  catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }
    }
}
